package com.packtpublishing.tddjava.ch03tictactoe;

import java.util.SimpleTimeZone;

public class TicTacToe {

    private Character[][] board = {{'\0', '\0', '\0'},{'\0', '\0', '\0'},{'\0', '\0', '\0'}};
    private char lastPlayer = '\0';
    private static final int SIZE = 3;
    public String play(int x, int y){
        checkAxis(x);
        checkAxis(y);
        lastPlayer = getNextPlayer();
        setBox(x, y, lastPlayer);
        if(isWin()){
            return lastPlayer + " is the winner";
        } else if(isDraw()){
            return "The result is draw";
        } else
            return "No Winner";
    }

    public boolean isWin(){
        int playerTotal = lastPlayer * SIZE;
        for(int i=0; i<SIZE; i++){
            if(board[0][i] + board[1][i] + board[2][i] == playerTotal){
                return true;
            } else if(board[i][0] + board[i][1] + board[i][2] == playerTotal){
                return true;
            } else if(board[0][0]+board[1][1]+board[2][2] == playerTotal){
                return true;
            }
        }
        return false;
    }

    public boolean isDraw(){
        for (int i=0; i<SIZE; i++){
            for(int j=0; j<SIZE; j++){
                if (board[i][j] == '\0') return false;
            }
        }
        return true;
    }


    public void checkAxis(int axis){
        if(axis < 1 || axis > 3) {
            throw new RuntimeException("X is outside board.");
        }
    }

    public void setBox(int x, int y, char lastPlayer){
        if(board[x-1][y-1]!='\0'){
            throw new RuntimeException("Box is occupied");
        } else {
            board[x-1][y-1]=lastPlayer;
        }
    }

    public char getNextPlayer(){
        if(lastPlayer == 'X'){
            return 'O';
        }
        return 'X';
    }
}
